package com.heaven.ojcodesandbox.controller;

import com.heaven.ojcodesandbox.JavaNativeCodeSandBox;
import com.heaven.ojcodesandbox.model.ExecuteCodeRequest;
import com.heaven.ojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author HeavenDirt
 * @Date 2024/7/25 16:17
 */

@RestController("/")
public class MainController {

    //保证api安全性，定义健全请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @GetMapping("/health")
    public String health() {
        return "OK";
    }

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest
            , HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse){
        //基本认证
        String header = httpServletRequest.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(header)){
            httpServletResponse.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
            throw new RuntimeException("executeCodeRequest is null");
        }
        return javaNativeCodeSandBox.executeCode(executeCodeRequest);
    }

}
